<?php
class Login extends CI_Controller {
	public function __construct() {
		parent::__construct();
		$this->load->helper('cookie');
		$this->load->model('login_model');
	}

	public function index() {
		return $this->view();
	}

	public function view() {
		$error = $this->session->flashdata('error');
		if (!$error) {
			$error = '&nbsp;';
		}
		$data['error'] = $error;
		$data['remembered'] = TRUE;
		$cookie = get_cookie('deliverer_remember_cookie');
		if (!$cookie) {
			$data['remembered'] = FALSE;
		}
		$this->load->view('templates/header', $data);
		$this->load->view('login/view');
		$this->load->view('templates/footer');
	}

	public function verify() {
		$loginData['username'] = $this->input->post('usernamel');
		$loginData['password'] = $this->input->post('passwordl');
		$remember = $this->input->post('rememberl');
		$name = $this->login_model->verify($loginData);
		if (!$name) {
			return $this->withLoginError('用户名或密码不正确!');
		}
		$this->session->set_userdata('username', $loginData['username']);
		$this->session->set_userdata('name', $name);
		if ($remember) {
			set_cookie(
				'deliverer_remember_cookie',
				json_encode($this->login_model->remember_cookie()),
				315360000
			);
			// delete_cookie('deliverer_remember_cookie');
		}
		return redirect('chat');
	}

	public function fast_login() {
		$cookie = get_cookie('deliverer_remember_cookie');
		$sessionData = $this->login_model->verify_remember_cookie(json_decode($cookie, TRUE));
		if (!$sessionData) {
			return $this->withLoginError('常用身份失效!');
		}
		$this->session->set_userdata('username', $sessionData['username']);
		$this->session->set_userdata('name', $sessionData['name']);
		return redirect('chat');
	}

	public function logout() {
		$this->session->unset_userdata('username');
		return redirect('login');
	}

	private function withLoginError($error = FALSE) {
		if ($error) {
			$this->session->set_flashdata('error', $error);
		}
		return redirect('login/view');
	}

}